package cn.meizhu.base.service.impl;

import cn.meizhu.base.service.ICodeService;
import cn.meizhu.util.SendMsgUtils;
import cn.meizhu.util.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class CodeServiceImpl implements ICodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void sendCode(Map<String, String> map) throws Exception {
        //获取请求参数
        String phone = map.get("phone");
        String codeType = map.get("codeType");
        String codeInRedis = (String) redisTemplate.opsForValue().get(phone + ":" + codeType);
        //产生随机验证码
        String code = StrUtils.getRandomString(6);
        if (codeInRedis != null){
            //获取上一次存储验证码的时间
            Long pretime = Long.valueOf(codeInRedis.split(":")[1]);
            if (System.currentTimeMillis() - pretime < 60*1000){
                throw new Exception("发送过于频繁，请稍后再试");
            }else {
                //获取上一次发送的验证码
                code = codeInRedis.split(":")[0];
            }
        }
        //发送验证码
        SendMsgUtils.sendCode(phone,code);
        System.out.println("验证码是:"+code);
        //把code 放到redis里面
        redisTemplate.opsForValue().set(phone+":"+codeType,code+":"+System.currentTimeMillis(),5, TimeUnit.MINUTES);
    }
}
